<template>
    <!-- TODO 详情后退 不同进入途径需要 返回步数不同 -->
    <page-frame class="expand-going" :goBackPage="detailGoBackPage">
        <template #header-title>
            {{ title }}
        </template>
        <div class="main h over-a-y">
            <page-line-text label="Machine" :text="taskDetailInfo.short"></page-line-text>
            <page-line-text label="Product" :text="taskDetailInfo.prod"></page-line-text>
            <page-line-text label="Jam 种类" :text="taskDetailInfo.contents?.category"></page-line-text>
            <page-line-text label="Jam Code" :text="taskDetailInfo.contents?.jam"></page-line-text>
            <page-line-text label="Jam Rate (总数/1个班时间)" :text="taskDetailInfo.contents?.rate"
                append-text=" 个"></page-line-text>
            <page-line-text label="Urgent" :text="getUrgentValue(taskDetailInfo.urgent)"></page-line-text>
            <page-line-text label="推荐维修方法">
                <check-list-box v-if="methods.methods" v-model:check-info="editForm.method"
                    v-model:check-other-info="editForm.method_other" :is-readonly="true" :list="methods.methods"
                    :is-multiple="true">
                </check-list-box>
            </page-line-text>
            <page-line-text label="录入机器码">
                <van-field v-model="editForm.machine" label="机器码" label-width="60" :error="machineIsError"
                    placeholder="请扫码录入机器码" />
            </page-line-text>
            <page-line-text label="历史趋势">
                <div class="h-200 w">
                    <chart class="w h" :loading="!historyChartLoading" :option="option1"></chart>
                </div>
                <div class="w f-c c8">AOlInspection Error趋势</div>
            </page-line-text>
            <page-line-text label="问题描述">
                <p v-if="methods.problems && methods.problems.length > 0" class="detail-p"
                    v-for="(pro, i) in methods.problems" :key="i">
                    <span class="detail-index">{{ i + 1 }}.</span>
                    <span class="detail-info">{{ pro.content }}.</span>
                </p>
                <p v-else>
                    <span class="detail-info">无</span>
                </p>
            </page-line-text>
            <page-line-text label="维修方法">
                <check-list-box v-if="methods.methods" v-model:check-info="editForm.method"
                    v-model:check-other-info="editForm.method_other" :list="methods.methods"
                    v-model:is-check-other="isCheckOther" :is-multiple="true"></check-list-box>
            </page-line-text>

            <page-line-text label="添加图片">
                <div class="w f-s-w">
                    <van-image v-for="(img, g) in uploadImageFileList " :key="g" width="100px" height="100px" fit="cover"
                        position="left" class="m-r3 m-b3 r2" :src="getImageFilePath(img)" />

                    <!-- 为避免手机端使用一次后再次点击上传无效，因此需要重新渲染按钮 -->
                    <upload-image v-if="isReloadUploadButton" class="w-100 h-100 b-i1 m-b3 r2" style="border-color:azure"
                        :upload-path="uploadImagePath" :is-success="true" @uploadSuccess="uploadSuccess"
                        @uploadError="uploadError">
                        <div class="w-100 h-100 f-c a-i-c" style="z-index:1">
                            <van-icon class="c8 fs32" name="plus" />
                        </div>
                    </upload-image>
                </div>
            </page-line-text>

            <div class="f-b box-b p-l10 p-r10 m-t10">
                <van-button type="primary" class="w4" round color="#EC9D0B" size="small"
                    @click="cancelOrTransparentOrder(true)">
                    申请取消
                </van-button>
                <van-button type="primary" class="w4" round color="#5b67ca" size="small" @click="completedOrder()">
                    完成工单
                </van-button>
            </div>
            <page-footer>已到达文件最底部</page-footer>

            <!-- <div class="p10">
                    <van-button type="primary" class="w" round color="#5b67ca" size="small"
                        @click="acceptOrder()">接单</van-button>
                    </div>
                    <div class="f-b box-b p-l10 p-r10 m-t10">
                    <van-button type="primary" class="w4 " round color="#EC9D0B" size="small"
                        @click="cancelOrTransparentOrder(true)">申请取消</van-button>
                    <van-button type="primary" class="w4 " round color="#5BC6CA" size="small"
                        @click="cancelOrTransparentOrder(false)">申请转交</van-button>
                    </div> 
            -->
        </div>
    </page-frame>
</template>

<script lang="ts">
import UploadImage from '@/components/upload-photo/index.vue'
import { getJamMethodInfo, uploadImagePath, type uploadImageType } from '@/apis/index'
import { CompletedApi } from '@/apis/completed/index'
import { DoingApi } from '@/apis/doing/doing'
import { type RequestCode } from '@/server/base'
import CheckListBox from '@/views/expand/components/check-list/index.vue'
import { PageFrame, PageFooter, PageLineText, Chart } from '@/importComponents'
import { option1 } from './res/index.res'
import PageBase from '@/views/mixins/page-base'

import { Notify, Toast, Dialog } from 'vant'

type DetailInfo = {
    id: string
    short: string
    prod: string
    contents: {
        [x: string]: any
    },
}


export default {
    mixins: [PageBase],
    components: { CheckListBox, PageFrame, PageFooter, PageLineText, Chart, UploadImage },
    data() {
        return {
            uploadImageFileList: [] as uploadImageType[],
            uploadImagePath,

            option1,
            historyChartLoading: true as boolean,
            editForm: {
                machine: '',
                method: [],
                method_other: ''
            } as any,
            isCheckOther: false,
            methods: { problems: [], methods: [] } as { problems: any[]; methods: any[] },

            /**为避免手机端使用一次后再次点击上传无效，因此需要重新渲染按钮 */
            isReloadUploadButton: true as boolean,
        }
    },
    computed: {
        isFormWait(): boolean {
            return this.$route.params?.formType === 'wait'
        },
        machineIsError() {
            return this.editForm.machine.toLocaleLowerCase() !== this.info.short.toLocaleLowerCase()
        },
        info(): DetailInfo {
            const itemStr: any = this.$route.params.value
            return this.getParamsByString(itemStr)
        },
        title(): string {
            return `JAM维修-工单${this.info.id}`
        },
        contents(): { [x: string]: any } {
            return this.taskDetailInfo.contents
        }
    },
    methods: {
        detailGoBackPage() {
            // debugger
            // const BACK_PATH = "/main/task";
            // if (window.history.state.back === BACK_PATH) {
            //     setTimeout(() => {
            //         window.location.reload();
            //     }, 500);
            // }
            this.goBackOrForward(this.isFormWait ? -2 : -1, true);
        },        /**
         *上传成功返回数据操作函数 
         */
        uploadSuccess(obj: uploadImageType) {
            if (!obj || !obj.path) {
                return;
            }
            this.uploadImageFileList.push(obj);
            this.uploadError();
        },
        uploadError(error?: any) {
            this.isReloadUploadButton = false;
            setTimeout(() => {
                this.isReloadUploadButton = true;
            }, 100);
        },
        getJamRentCharts() {
            if (!this.taskDetailInfo || !this.taskDetailInfo.contents.jam) {
                return
            }
            this.historyChartLoading = true
            DoingApi.getJamRent(this.taskDetailInfo.contents.jam, this.taskDetailInfo.machine)
                .then((res: RequestCode) => {
                    const _data = res.data
                    this.option1.xAxis.data = _data.xAxis
                    this.option1.series[0].data = _data.series
                    this.historyChartLoading = false
                })
                .catch(error => { })
        },
        //获取jamCode 注意事项和方法
        getJamCodeMethodInfo() {
            if (!this.taskDetailInfo || !this.taskDetailInfo.contents.jam) {
                return
            }
            getJamMethodInfo(this.taskDetailInfo.contents.jam)
                .then((res: RequestCode) => {
                    this.methods = res.data || { problems: [], methods: [] }
                })
                .catch(error => { })
        },
        cancelOrTransparentOrder(isCancel = true) {
            this.$router.push({
                name: 'wait-detail-reject',
                params: {
                    value: this.getParamsString(this.taskDetailInfo),
                    type: isCancel ? 'cancel' : 'transformation'
                }
            })
        },
        /**
         * 完成工单
         */
        completedOrder() {
            if (this.machineIsError) {
                Notify({ type: 'danger', message: '扫码录入机器和当前待维修机器不一致！' })
                return
            }
            const { method, method_other } = this.editForm
            if ((!method || (method.length <= 0 && !this.isCheckOther)) && !method_other) {
                Notify({ type: 'danger', message: '请选择或填写维修方法' })
                return
            }
            Dialog.confirm({
                title: '提示',
                message: `确认提交【${this.title}】状态为【已完成】吗?`
            })
                .then(() => {
                    //去除重复项
                    let methodInfo: string[] = method.map((meth: any) => meth.content);
                    methodInfo = [...new Set(methodInfo)];
                    
                    CompletedApi.postCompleted({
                        id: this.info.id,
                        method: methodInfo,
                        method_other: this.isCheckOther ? '' : method_other,
                        file_id: this.uploadImageFileList.map((img: uploadImageType) => img.id) as string[],
                    })
                        .then((res: RequestCode) => {
                            Toast('工单操作完成成功！')
                            this.goBackOrForward(this.isFormWait ? -2 : -1, true)
                        })
                        .catch(error => {
                            Notify({ type: 'danger', message: error.msg })
                        })
                })
                .catch(() => { })
        }
    },
    created() {
        this.getTaskDetailById(this.info.id, () => {
            this.getJamRentCharts()
            this.getJamCodeMethodInfo()
        });
    }
}
</script>

<style lang="scss">
.expand-going {
    .detail-p {
        font-size: 14px;

        .detail-index {
            padding-right: 4px;
            @extend .c8;
        }

        line-height: 22px;
    }

    .checkbox-list-group {
        .van-cell {
            padding-left: 2px !important;
            padding-right: 2px !important;
            color: #10275a;
        }
    }

    .van-cell-group {
        margin: 0px !important;
    }
}
</style>
